package org.hanbo.code.repository.action;

//import java.util.List;

import org.hanbo.code.repository.exception.CodeSnippetActionNotAuthorizedException;
import org.hanbo.code.repository.exception.CodeSnippetExceptionBase;
import org.hanbo.code.repository.exception.ErrorDescription;
import org.hanbo.code.repository.persistence.entity.CodeSnippet;
import org.hanbo.code.repository.persistence.entity.CodeSnippetDAO;
import org.hanbo.code.repository.persistence.entity.RegisteredUser;

import com.google.appengine.api.datastore.Key;

public class AddCodeSnippetAction  extends CodeSnippetActionBase
{
	private static final long serialVersionUID = 4599383519810767431L;
	
	private ErrorDescription errorDesc;
	
	public AddCodeSnippetAction()
	{ }
	
	public void validate()
	{
		if (subjectField == null || subjectField.length() <= 0)
		{
			addFieldError("subjectField", "The subject field can't be empty");
		}
		if (codeSnippetField == null || codeSnippetField.length() <= 0)
		{
			addFieldError("codeSnippetField", "The code snippet field can't be empty");
		}
		if (relatedCommentsField == null || relatedCommentsField.length() <= 0)
		{
			addFieldError("relatedCommentsField", "The comments field can't be empty");
		}
	}
		
	public String getNextActionPage()
	{
		return "/RetrieveCodeSnippetById?type=CodeSnippet&id=" + this.snippetId;
	}

	public String getRedirectDisplayMessage()
	{
		return "Code Snippet [id: " + this.snippetId + ", Subject: " + this.subjectField + "] was saved successfully.";
	}

	public String execute()
	{
		if (!checkLogin())
		{
			return super.getCurrentStageValue();
		}
		
		if (!super.checkRegistration())
		{
			return super.getCurrentStageValue();
		}
		
		RegisteredUser regUser = super.getRegisteredUser();
		CodeSnippetDAO dao = new CodeSnippetDAO();
		try
		{
		
			if (regUser.getDisableByAdmin() || !regUser.getUserActiveStatus())
			{
				String errorMsg = "User is current in disabled mode.";
				if (regUser.getDisableByAdmin())
				{
					 errorMsg = errorMsg + " Disabled by Administrator.";
				}
				throw new CodeSnippetActionNotAuthorizedException(errorMsg);
			}
	
			CodeSnippet snippetToSave = super.convertToCodeSnippet(regUser.getUserName());
		
			dao.acquirePersistenceManager();
			Key snippetId = dao.persistCodeSnippet(snippetToSave);
			this.setSnippetId(snippetId.getId());
			return SUCCESS;
		}
		catch (CodeSnippetExceptionBase e)
		{
			errorDesc = new ErrorDescription(e);
			return ERROR;
		}
		catch(Exception e)
		{
			errorDesc = new ErrorDescription(1000, e);
			return ERROR;
		}
		finally
		{
			dao.releasePersistenceManager();
		}
	}
	
    public String getRedirectLogin()
    {
    	return super.createLogInLink("../SaveCodeSnippet.action");
    }
    
    public ErrorDescription getErrorDescription()
    {
    	return this.errorDesc;
    }
}
